package com.newgrand.ng5.web.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：minyang
 * @date ：Created in 2019/8/15 18:32
 */
@Aspect
@Component
public class HttpLog {

    public static final Logger logger = LoggerFactory.getLogger(HttpLog.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution( * com.newgrand.ng5.web.controller.*.*(..))")
    public void httpLog2() {

    }

    @Before("httpLog2()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //URL
        logger.debug("url:{}", request.getRequestURL());
        //Request method
        logger.debug("method:{}", request.getMethod());
        //IP
        logger.debug("ip:{}", request.getRemoteAddr());
        //Class method name
        logger.debug("method:{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // Argument
        //logger.debug("args:{}", JSONUtil.toJSONString(joinPoint.getArgs()));
    }

    @After("httpLog2()")
    public void doAfter() {
        logger.debug("request cost time:{} ms", System.currentTimeMillis() - startTime.get());
    }

    @AfterReturning(returning = "object", pointcut = "httpLog2()")
    public void afterReturning(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            logger.debug("response:{}", mapper.writeValueAsString(object));
        } catch (Exception e) {

        }

    }
}
